"""
python 项目练习 画幅好画
"""
from urllib.request import urlopen
from reportlab.graphics.shapes import *
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics import renderPDF

def main():
    # 数据源URL，指向太阳黑子预测数据文件
    URL =  'file:./item2_predict.txt'
    # 注释字符，用于识别数据文件中的注释行
    COMMENT_CHARS = '#:'

    # 创建绘图对象，尺寸为400x200像素
    drawing = Drawing(400, 200)

    # 存储从URL读取并解析的数据
    data = []

    # 从URL读取数据文件，解析非注释行并将数据转换为浮点数存储
    for line in urlopen(URL).readlines():
        # 将字节串解码为字符串
        line = line.decode('utf-8')
        if not line.isspace() and not line[0] in COMMENT_CHARS:
            data.append([float(n) for n in line.split()])

    # 从数据中提取预测值、最高值、最低值和时间序列
    pred = [row[2] for row in data]
    high = [row[3] for row in data]
    low = [row[4] for row in data]
    times = [row[0] + row[1]/12.0 for row in data]

    # 创建折线图对象并设置其属性
    lp = LinePlot()
    lp.x = 50
    lp.y = 50
    lp.height = 125
    lp.width = 300
    # 将 zip 对象转换为列表以兼容 ReportLab
    lp.data = [list(zip(times, pred)), list(zip(times, high)), list(zip(times, low))]
    lp.lines[0].strokeColor = colors.blue
    lp.lines[1].strokeColor = colors.red
    lp.lines[2].strokeColor = colors.green

    # 将折线图添加到绘图对象中
    drawing.add(lp)
    # 添加标题文本
    drawing.add(String(250,150,'Sunspots',fontSize = 14, fillColor = colors.red))

    # 将绘制的图形保存为PDF文件
    renderPDF.drawToFile(drawing, 'report3.pdf', 'Sunspots')


if __name__ == '__main__':
    main()